package com.homedo.microservice.wechat.personal.secretary.entity;

import com.homedo.microservice.wechat.personal.secretary.service.PersonalBotService;
import lombok.Data;

import java.util.Collections;
import java.util.List;

@Data
public class PersonalBotBiz {
    private PersonalBotService botService;
    private List<Biz> bizs;

    private PersonalBot bot;

    public PersonalBotBiz(PersonalBot bot, PersonalBotService botService) {
        this.bot = bot;
        this.botService = botService;
    }

    public void loadBizs() {
        List<Biz> bizs = botService.getBizByAccount(bot.config().sysLoginAccount(), null);
        if (bizs != null && bizs.size() > 0) {
            Collections.sort(bizs);
            bizs.forEach(e -> {
                e.setBotBiz(this);
            });
            this.bizs = bizs;
        }
    }

    public String getReplyBizMsg() {
        if (bizs != null && bizs.size() > 0) {
            StringBuilder replyBizMsg = new StringBuilder("请发送以下序号执行对应操作:\n");
            bizs.forEach(e -> {
                replyBizMsg.append(e.getCode()).append(" ").append(e.getName()).append("\n");
            });
            return replyBizMsg.toString();
        } else {
            return "未办理业务或重试";
        }
    }

    public void dealBiz(String bizCode) {
        boolean bizExist = botService.checkBizExist(bizCode, null);

        if (!bizExist) {
            bot.sendMsgToFileHelper("你说什么，我怎么听不懂？[疑问]\n查看已办业务，请回复“帮助”");
            return;
        }

        if (bizs != null && bizs.size() > 0) {
            Biz biz = this.getBiz(bizCode);
            if (biz == null) {
                bot.sendMsgToFileHelper("尚未开通此业务或重试");
            } else {
                biz.dealBiz();
            }
        } else {
            bot.sendMsgToFileHelper("未办理业务或重试");
        }
    }

    private Biz getBiz(String bizCode) {
        for (Biz biz : bizs) {
            if (biz.getCode().equals(bizCode)) {
                return biz;
            }
        }
        return null;
    }
}
